<?php
/**
 * ***********************************************************************************
 * 咨询鲤 PC端知识店铺-个人中心
 * 
 * @author Mr.RJH
 * @date 2025-09-16
 * @email<15213026209@163.com>
 * ***********************************************************************************
 */
namespace app\controller;

use app\BaseController;

use think\facade\Db;
use app\model\product\ZxlKnowStoreProductModel;
use app\model\product\ZxlKnowStoreProductAttrModel;
use app\model\product\ZxlKnowStoreCourseContentModel;
use app\model\product\ZxlKnowStoreExamContentModel;

use app\model\user\ZxlTalentUserModel;
use app\model\user\ZxlKnowStoreAdviceModel;
use app\model\user\ZxlKnowStoreAddressModel;
use app\model\user\DouyinAreaModel;
use app\model\user\ZxlKnowStoreCouponModel;
use app\model\user\ZxlKnowStoreCouponReceiveModel;
use app\model\user\ZxlKnowStoreUserBaseModel;
use app\model\user\ZxlKnowStoreUserDistributionLogModel;
use app\model\user\ZxlCashOutRecordModel;
use app\model\user\ZxlKnowStoreSharerUserModel;
use app\model\user\ZxlKnowStoreBalanceLogModel;
use app\model\user\ZxlKnowStoreCollectModel;
use app\model\user\ZxlKnowStorePowerModel;
use app\model\user\ZxlApplyRedeemCodeLogModel;
use app\model\user\ZxlKnowStoreLiveClassModel;
use app\model\user\ZxlKnowStoreLiveClassHourModel;
use app\model\user\ZxlKnowStoreLikeLogModel;
use app\model\user\ZxlKnowStoreQuestionPracticeModel;
use app\model\user\ZxlKnowStoreSavingsCardNumberModel;
use app\model\user\ZxlKnowStoreMemberLevelModel;
use app\model\user\ZxlKnowStoreMemberLevelCardModel;
use app\model\user\ZxlKnowStoreUserLevelModel;

use app\model\question\ZxlKnowStoreQuestionModel;

use app\model\order\ZxlKnowStoreOrderModel;
use app\model\order\ZxlKnowStoreOrderDetailModel;

use app\model\sms\ZxlSmsVerifyCodeModel;

use app\service\ProductService;
use app\service\KnowStoreApiService;

class User extends BaseController
{
    /**
     * 个人资料
     * 
     * @return mixed
     */
    public function info()
    {
        if ($this->request->isPost()) {
            try {
                $post = $this->request->post();
                
                $result = ZxlTalentUserModel::where('id', $this->user_id)->update($post);
                if ($result) {
                    $user = ZxlTalentUserModel::find($this->user_id);
                    $user = $user->toArray();
                    session('user', $user);
                    return json(['code' => 0, 'msg' => '修改成功']);
                } else {
                    return json(['code' => 1, 'msg' => '修改失败']);
                }
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            } 
        }
        $info = ZxlTalentUserModel::find($this->user_id);
        if ($info['mobile']) {
            $info['mobile'] = substr_replace($info['mobile'], str_repeat('*', 4), 3, 4);
        }
        $base = ZxlKnowStoreUserBaseModel::where('user_id', $info['id'])->find();
        if ($base['id_card']) {
            $base['id_card'] = substr_replace($base['id_card'], str_repeat('*', 8), 6, 8);
        }
        $info['base'] = $base;

        // 获取用户会员信息
        $user_level = ZxlKnowStoreUserLevelModel::where('user_id', $this->user_id)->find();

        $info['is_member_level'] = 0;
        if ($user_level) {
            $info['is_member_level'] = 1;
            if ($user_level['end_time'] > 0 && $user_level['end_time'] < time()) {
                $info['is_member_level'] = 0;
            }
        }
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 修改昵称
     * 
     * @return mixed
     */
    public function update_nickname()
    {
        $info = ZxlTalentUserModel::find($this->user_id);

        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 修改实名
     * 
     * @return mixed
     */
    public function update_realname()
    {
        if ($this->request->isPost()) {
            try {
                $post = $this->request->post();
                
                $result = ZxlKnowStoreUserBaseModel::where('user_id', $this->user_id)->update($post);
                if ($result) {
                    return json(['code' => 0, 'msg' => '修改成功']);
                } else {
                    return json(['code' => 1, 'msg' => '修改失败']);
                }
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            } 
        }
        $info = ZxlKnowStoreUserBaseModel::where('user_id', $this->user_id)->find();
        
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 修改密码
     * 
     * @return mixed
     */
    public function update_pass()
    {
        if ($this->request->isPost()) {
            try {
                $post = $this->request->post();
                
                $m_id = $this->request->m_id;
                $verify_code_log = ZxlSmsVerifyCodeModel::where(['mobile' => $post['mobile']])->order('create_time', 'desc')->find();
                if ($verify_code_log['code'] != $post['verify_code']) {
                    return json(['code' => 1, 'msg' => '短信验证码错误，请重新输入']);
                }
                if (time() > $verify_code_log['expire_time']) {
                    return json(['code' => 1, 'msg' => '短信验证码已过期，请重新获取']);
                }
                
                $new_pass = md5(md5($post['password']));
                $result = ZxlTalentUserModel::where('id', $this->user_id)->update(['password' => $new_pass]);
                if ($result) {
                    return json(['code' => 0, 'msg' => '修改成功']);
                } else {
                    return json(['code' => 1, 'msg' => '修改失败']);
                }
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            } 
        }
        $info = ZxlTalentUserModel::find($this->user_id);

        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 意见反馈
     * 
     * @return mixed
     */
    public function feedback()
    {
        if ($this->request->isPost()) {
            try {
                $post = $this->request->post();
                unset($post['file']);

                $post['m_id'] = $this->request->m_id;
                $post['user_id'] = $this->user_id;
                $post['create_time'] = date('Y-m-d H:i:s');
                if (isset($post['imgs']) && $post['imgs']) {
                    $post['imgs'] = implode(',', $post['imgs']);
                }
                $result = ZxlKnowStoreAdviceModel::insert($post);
                if ($result) {
                    return json(['code' => 0, 'msg' => '操作成功']);
                } else {
                    return json(['code' => 1, 'msg' => '操作失败']);
                }
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            } 
        }
        $info = ZxlTalentUserModel::find($this->user_id);

        $this->assign('getAdviceType', ZxlKnowStoreAdviceModel::getAdviceType());
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 收货地址
     * 
     * @return mixed
     */
    public function address()
    {
        if ($this->request->isPost()) {

            $limit = $this->request->param('limit', 10);
            $page = $this->request->param('page',1);
            
            $m_id = $this->request->m_id;
            try {

                //查询条件
                $where = function($q)use($m_id){
                    $q->where('m_id', $m_id);
                    $q->where('user_id', $this->user_id);
                };

                $query = ZxlKnowStoreAddressModel::where($where);
                $list = $query->order('id', 'desc')->paginate($limit,false,['page'=>$page])->toArray();
                
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
            return json(['code' => 0,'msg' => 'SUCCESS','count' => $list['total'],'data' => $list['data']]);
        }

        return $this->fetch();
    }

    /**
     * 收货地址-编辑
     * 
     * @return mixed
     */
    public function address_edit()
    {
        if ($this->request->isPost()) {
            try {
                $post = $this->request->post();
                
                if (!isset($post['default'])) {
                    $post['default'] = 2;
                }

                // 地区处理
                $district = DouyinAreaModel::find($post['district_id']);
                $city = DouyinAreaModel::where('id', $district['parent_id'])->find();
                $province = DouyinAreaModel::where('id', $city['parent_id'])->value('name');
                $post['region'] = $province.'-'.$city['name'].'-'.$district['name'];
                unset($post['district_id']);
                if (!$post['id']) {
                    $post['m_id'] = $this->request->m_id;
                    $post['user_id'] = $this->user_id;
                    $post['create_time'] = time();
                    $result = ZxlKnowStoreAddressModel::insertGetId($post);
                    $address_id = $result;
                } else {
                    $address_id = $post['id'];
                    $post['update_time'] = time();
                    $result = ZxlKnowStoreAddressModel::where('id', $post['id'])->update($post);
                }
                if ($result) {
                    if (isset($post['default']) && $post['default'] == 1) {
                        ZxlKnowStoreAddressModel::where('id', '<>', $address_id)->where(['user_id' => $this->user_id])->update(['default' => 2, 'update_time' => time()]);
                    }
                    return json(['code' => 0, 'msg' => '操作成功']);
                } else {
                    return json(['code' => 1, 'msg' => '操作失败']);
                }
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            } 
        }
        $id = $this->request->param('id');
        $info = ZxlKnowStoreAddressModel::find($id);
        if ($info) {
            $areas = explode('-', $info['region']);
            $region = DouyinAreaModel::whereIn('name', $areas)->select()->toArray();
            if (!$info['district_id']) {
                $info['district_id'] = $region[2]['id'];
            }
        }
        $this->assign('area_list', DouyinAreaModel::getAreaList());
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 收货地址-删除
     * 
     * @return json
     */
    public function address_delete()
    {
        if ($this->request->isDelete()) {
            $post = $this->request->post();

            try {
                $info = ZxlKnowStoreAddressModel::find($post['id']);
                if (!$info) {
                    return json(['code' => 1, 'msg' => '数据查询失败，请刷新重试']);
                }
                if ($info['default'] == 1) {
                    return json(['code' => 1, 'msg' => '默认地址不可删除']);
                }
                $result = ZxlKnowStoreAddressModel::where('id',$post['id'])->delete();
                
                if ($result) {
                    return json(['code' => 0, 'msg' => '操作成功']);
                } else {
                    return json(['code' => 1, 'msg' => '操作失败']);
                }

            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => $e->getMessage()]);
            } 
            
        }
    }

    /**
     * 优惠券
     * 
     * @return mixed
     */
    public function coupon()
    {
        if ($this->request->isPost()) {

            $limit = $this->request->param('limit', 10);
            $page = $this->request->param('page',1);
            
            $coupon_status = $this->request->param('coupon_status');
            $m_id = $this->request->m_id;
            try {

                //查询条件
                $where = function($q)use($m_id, $coupon_status){
                    $q->where('m_id', $m_id);
                    $q->where('user_id', $this->user_id);
                    $q->where('coupon_status', $coupon_status);
                };
                $query = ZxlKnowStoreCouponReceiveModel::where($where);
                $list = $query->order('receive_time', 'desc')->paginate($limit,false,['page'=>$page])->toArray();
                foreach ($list['data'] as &$v) {
                    $v['valid_begin_time'] = date('Y-m-d', $v['valid_begin_time']);
                    $v['valid_end_time'] = date('Y-m-d', $v['valid_end_time']);
                    $v['discount_type'] = ZxlKnowStoreCouponReceiveModel::getCouponType($v['discount_type']);
                }
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
            return json(['code' => 0,'msg' => 'SUCCESS','count' => $list['total'],'data' => $list['data']]);
        }

        return $this->fetch();
    }

    /**
     * 我的收益
     * 
     * @return mixed
     */
    public function income()
    {
        if ($this->request->isPost()) {

            $limit = $this->request->param('limit', 10);
            $page = $this->request->param('page',1);
            
            $type = $this->request->param('type');
            $m_id = $this->request->m_id;
            try {

                //查询条件
                if ($type == 1) {
                    $where = function($q){
                        $q->where('user_id', $this->user_id);
                    };
                    $query = ZxlKnowStoreUserDistributionLogModel::where($where);
                } else {
                    $where = function($q){
                        $q->where('to_id', $this->user_id);
                        $q->where('mark', 2);
                        $q->where('id_type', 3);
                        $q->where('ismanager', 1);
                    };
                    $query = ZxlCashOutRecordModel::where($where);
                }
                
                $list = $query->order('create_time', 'desc')->paginate($limit,false,['page'=>$page])->toArray();
                foreach ($list['data'] as &$v) {
                    $v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
                    if (isset($v['alipay'])) {
                        $v['alipay'] = json_decode($v['alipay'], true);
                    }
                }
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
            return json(['code' => 0,'msg' => 'SUCCESS','count' => $list['total'],'data' => $list['data']]);
        }
        $info = ZxlKnowStoreUserBaseModel::where(['user_id' => $this->user_id])->find();

        // 获取已提现金额
        $info['withdrawn_amount'] = ZxlCashOutRecordModel::where(['to_id' => $this->user_id, 'mark' => 2, 'id_type' => 3, 'ismanager' => 1, 'audit_status' => 3])->sum('price');
        
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 我的推广
     * 
     * @return mixed
     */
    public function promotion()
    {
        if ($this->request->isPost()) {

            $limit = $this->request->param('limit', 10);
            $page = $this->request->param('page',1);
            $product_type = $this->request->param('product_type');

            $m_id = $this->request->m_id;
            try {
                $product_list = ZxlKnowStoreSharerUserModel::where(['user_id' => $this->user_id, 'm_id' => $m_id, 'is_delete' => 0, 'status' => 1])->value('product_list');
                
                $product_ids = [];
                $ratio = [];
                if ($product_list) {
                    $product_lists = json_decode($product_list, true);
                    foreach ($product_lists as $val) {
                        $product_ids[] = $val['product_id'];
                        $ratio[$val['product_id']] = $val['ratio'];
                    }  
                } 
                $where = function($q)use($m_id, $product_ids, $product_type){
                    $q->where('m_id', $m_id);
                    $q->whereIn('id', $product_ids);
                    $q->where('product_type', $product_type);
                };
                $query = ZxlKnowStoreProductModel::where($where);
                $list = $query->order('create_time', 'desc')->field('id,product_type,name,head_imgs,background_color,sub_title')->paginate($limit,false,['page'=>$page])->toArray();
                foreach ($list['data'] as &$v) {
                    if ($v['product_type'] == 10) {
                        $v['head_imgs'] = '/static/images/exam.png';
                    } else {
                        $v['head_imgs'] = $v['head_imgs'] ? explode(',',$v['head_imgs'])[0] : '/static/images/no_pic_1.png';
                    }
                    $v['product_type_text'] = ZxlKnowStoreProductModel::getPcProductType($v['product_type']);
                    $v['href'] = ZxlKnowStoreProductModel::getPcProductDetailHref($v['product_type'], $v['id']);
                    $v['ratio'] = $ratio[$v['id']];

                    // 获取规格最低售价 最高售价
                    $min_price = ZxlKnowStoreProductAttrModel::where(['product_id' => $v['id'], 'is_delete' => 0, 'status' => 1])->min('sale_price');
                    $max_price = ZxlKnowStoreProductAttrModel::where(['product_id' => $v['id'], 'is_delete' => 0, 'status' => 1])->max('sale_price');

                    $v['min_commission'] = number_format(($min_price * $v['ratio']) / 100, 2);
                    $v['max_commission'] = number_format(($max_price * $v['ratio']) / 100, 2);
                }
                
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
            return json(['code' => 0,'msg' => 'SUCCESS','count' => $list['total'],'data' => $list['data']]);
        }
        $this->assign('getPcProductType', ZxlKnowStoreProductModel::getPcProductType());
        return $this->fetch();
    }

    /**
     * 推广分享
     * 
     * @return mixed
     */
    public function promotion_share()
    {
        if ($this->request->isPost()) {

            $id = $this->request->param('id');
            
            $m_id = $this->request->m_id;
            try {
                $knowStoreApiService = new KnowStoreApiService($m_id, $this->user_token);
                $result = $knowStoreApiService->createPoster($id);
                
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
            return json(['code' => 0,'msg' => 'SUCCESS', 'data' => $result]);
        }
        $id = $this->request->param('id');

        $this->assign('id', $id);
        return $this->fetch();
    }

    /**
     * 会员储值
     * 
     * @return mixed
     */
    public function balance()
    {
        if ($this->request->isPost()) {

            $limit = $this->request->param('limit', 10);
            $page = $this->request->param('page',1);
            
            $type = $this->request->param('type');
            $m_id = $this->request->m_id;
            try {

                //查询条件
                $where = function($q)use($m_id, $type){
                    $q->where('user_id', $this->user_id);
                    $q->where('m_id', $m_id);
                    if ($type > 0) {
                        if ($type == 1) {
                            $q->where('amount', '>', 0);
                        } else {
                            $q->where('amount', '<', 0);
                        }
                    }
                    
                };
                $query = ZxlKnowStoreBalanceLogModel::where($where);
                $list = $query->order('create_time', 'desc')->paginate($limit,false,['page'=>$page])->toArray();
                foreach ($list['data'] as &$v) {
                    $v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
                }
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
            return json(['code' => 0,'msg' => 'SUCCESS','count' => $list['total'],'data' => $list['data']]);
        }
        $money = ZxlKnowStoreUserBaseModel::where('user_id', $this->user_id)->value('money');

        $this->assign('money', $money);
        return $this->fetch();
    }

    /**
     * 我的收藏
     * 
     * @return mixed
     */
    public function favorites()
    {
        if ($this->request->isPost()) {

            $limit = $this->request->param('limit', 10);
            $page = $this->request->param('page',1);
            $product_type = $this->request->param('product_type');

            $m_id = $this->request->m_id;
            try {
                $where = function($q)use($m_id, $product_type){
                    $q->where('c.m_id', $m_id);
                    $q->where('c.user_id', $this->user_id);
                    $q->where('c.type', $product_type);
                };
                $query = ZxlKnowStoreCollectModel::alias('c')->where($where)->leftJoin('zxl_know_store_product p','c.product_id = p.id');
                $list = $query->field('c.*,p.name,p.head_imgs,p.product_type,p.background_color,p.sub_title,p.virtual_sales,p.real_sales')->order('create_time', 'desc')->paginate($limit,false,['page'=>$page])->toArray();
                foreach ($list['data'] as &$v) {
                    $attr = ZxlKnowStoreProductAttrModel::where(['product_id' => $v['product_id'], 'is_delete' => 0, 'status' => 1])->order('sale_price', 'asc')->find();
                    $v['sale_price'] = $attr['sale_price'] ?? '0.00';
                    $v['original_price'] = $attr['original_price'] ?? '0.00';
                    if ($v['product_type'] == 10) {
                        $v['head_imgs'] = '/static/images/exam.png';
                    } else {
                        $v['head_imgs'] = $v['head_imgs'] ? explode(',',$v['head_imgs'])[0] : '/static/images/no_pic_1.png';
                    }
                    
                    $v['product_type_text'] = ZxlKnowStoreProductModel::getPcProductType($v['product_type']);
                    $v['href'] = ZxlKnowStoreProductModel::getPcProductDetailHref($v['product_type'], $v['product_id']);
                }
                
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
            return json(['code' => 0,'msg' => 'SUCCESS','count' => $list['total'],'data' => $list['data']]);
        }
        $this->assign('getPcProductType', ZxlKnowStoreProductModel::getPcProductType());
        return $this->fetch();
    }

    /**
     * 收藏/取消商品
     * 
     * @return json
     */
    public function favorites_product()
    {
        if ($this->request->isPost()) {

            $product_id = $this->request->param('product_id');

            $m_id = $this->request->m_id;
            try {
                $product = ZxlKnowStoreProductModel::find($product_id);
                if (!$product) {
                    return json(['code' => 1,'msg' => '操作失败，请刷新页面重试']);
                }
                $model = ZxlKnowStoreCollectModel::where(['user_id' => $this->user_id, 'product_id' => $product_id])->find();
                if (!$model) {
                    $model = new ZxlKnowStoreCollectModel();
                    $model->m_id = $m_id;
                    $model->user_id = $this->user_id;
                    $model->type = $product['product_type'];
                    $model->product_id = $product['id'];
                    $model->create_time = time();
                    $model->save();

                    $msg = '收藏成功';
                    $is_favorites = 1;
                } else {
                    $model->delete();
                    $msg = '取消收藏';
                    $is_favorites = 0;
                }
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
            return json(['code' => 0,'msg' => $msg, 'data' => $is_favorites]);
        }
    }

    /**
     * 移除我的收藏
     * 
     * @return json
     */
    public function favorites_del()
    {
        if ($this->request->isPost()) {

            $product_id = $this->request->param('product_id');

            $m_id = $this->request->m_id;
            try {
                $product = ZxlKnowStoreProductModel::find($product_id);
                if (!$product) {
                    return json(['code' => 1,'msg' => '移除失败，请刷新页面重试']);
                }
                ZxlKnowStoreCollectModel::where(['user_id' => $this->user_id, 'product_id' => $product_id])->delete();
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
            return json(['code' => 0,'msg' => '移除成功']);
        }
    }

    /**
     * 我的订单
     * 
     * @return mixed
     */
    public function order()
    {
        if ($this->request->isPost()) {
            $limit = $this->request->param('limit');
            $page = $this->request->param('page',1);
            $status = $this->request->param('status');
            
            $m_id = $this->request->m_id;
            try {
                //查询条件
                $where = function($q)use($m_id, $status){
                    $q->where('m_id', $m_id);
                    $q->where('user_id', $this->user_id);
                    if ($status != '') {
                        if ($status == 4) {
                            $q->where('is_comment', 0);
                            $q->where('status', $status);
                        } else if ($status == 6) {
                            $q->whereIn('status', [6,7,8]);
                        } else {
                            $q->where('status', $status);
                        }
                    }
                };
                $query = ZxlKnowStoreOrderModel::with("orderGoods")->where($where);
                $list = $query->field('id,order_no,status,order_price,pay_price,create_time')->order('create_time','desc')->paginate($limit,false,['page'=>$page])->toArray();
                foreach ($list['data'] as &$v) {
                    $v['status_text'] = ZxlKnowStoreOrderModel::getOrderStatus($v['status']);
                    $v['create_time'] = date('Y-m-d', $v['create_time']);
                    foreach ($v['orderGoods'] as &$val) {
                        $product_type = ZxlKnowStoreProductModel::where('id', $val['product_id'])->value('product_type');
                        $val['href'] = ZxlKnowStoreProductModel::getPcProductDetailHref($product_type, $val['product_id']);
                    }
                }
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
            return json(['code' => 0,'msg' => 'SUCCESS','count' => $list['total'],'data' => $list['data']]);
        }
        return $this->fetch();
    }

    /**
     * 订单详情
     * 
     * @return mixed
     */
    public function order_detail()
    {
        $order_id = $this->request->param('order_id');
        $info = ZxlKnowStoreOrderModel::where(['m_id' => $this->request->m_id, 'id' => $order_id, 'user_id' => $this->user_id])->find();
        if (!$info) {
            return $this->fetch('error/http404');
        }
        $info['pay_type_text'] = ZxlKnowStoreOrderModel::getPayType($info['pay_type']);

        if ($info['user_address']) {
            $info['user_address'] = json_decode($info['user_address'], true);
        }
        if ($info['express_info']) {
            $info['express_info'] = json_decode($info['express_info'], true);
        }
        $info['status_text'] = ZxlKnowStoreOrderModel::getOrderStatus($info['status']);
        $order_goods = ZxlKnowStoreOrderDetailModel::where('order_id', $order_id)->field('product_id,img,product_name,attr_name,price,num')->select()->toArray();
        foreach ($order_goods as &$v) {
            $product_type = ZxlKnowStoreProductModel::where('id', $v['product_id'])->value('product_type');
            $v['product_type_text'] = ZxlKnowStoreProductModel::getPcProductType($product_type);
            $v['href'] = ZxlKnowStoreProductModel::getPcProductDetailHref($product_type, $v['product_id']);
        }
        $info['order_goods'] = $order_goods;

        $productService = new ProductService($this->request->m_id);
        // 随机推荐
        $list = $productService->rand_recommend_product(12);

        $this->assign('list', $list);
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 取消订单
     * 
     * @return mixed
     */
    public function cancel_order()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $m_id = $this->request->m_id;
            try {
                $knowStoreApiService = new KnowStoreApiService($m_id, $this->user_token);
                $result = $knowStoreApiService->cancelOrder($post['id'], $post['text']);
                if ($result) {
                    return json(['code' => 0, 'msg' => '取消成功']);
                } else {
                    return json(['code' => 1, 'msg' => '取消失败']);
                }
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
        }
        $id = $this->request->param('id');
        
        $reson_list = ZxlKnowStoreOrderModel::cancelReson();
        $this->assign('id', $id);
        $this->assign('reson_list', $reson_list);
        return $this->fetch();
    }

    /**
     * 我的课程
     * 
     * @return mixed
     */
    public function course()
    {
        if ($this->request->isPost()) {
            $limit = $this->request->param('limit');
            $page = $this->request->param('page',1);
            $keyword = $this->request->param('keyword');
            
            $m_id = $this->request->m_id;
            try {
                //查询条件
                $where = function($q)use($m_id, $keyword){
                    $q->where('up.m_id', $m_id);
                    $q->where('up.user_id', $this->user_id);
                    $q->where('up.power_type', 3);
                    if ($keyword != '') {
                        $q->where('p.name|p.sub_title', 'like','%'.trim($keyword).'%');
                    }
                };
                $query = ZxlKnowStorePowerModel::alias('up')->where($where)->leftJoin('zxl_know_store_product p','up.product_id = p.id');
                $list = $query->field('up.*,p.name,p.p_product_id,p.head_imgs,p.virtual_sales,p.real_sales')->order('create_time', 'desc')->paginate($limit,false,['page'=>$page])->toArray();
                foreach ($list['data'] as &$v) {
                    $v['head_imgs'] = $v['head_imgs'] ? explode(',',$v['head_imgs'])[0] : '/static/images/no_pic_1.png';
                    $v['product_type_text'] = ZxlKnowStoreProductModel::getPcProductType($v['power_type']);

                    if($v['end_time'] == 0) {
                        $v['end_time'] = "永久有效";
                    } else {
                        $v['end_time'] = date("Y-m-d H:i:s", $v['end_time']);
                    }

                    // 课程：课节数
                    if ($v['p_product_id']) {
                        $v['catalog_number'] = ZxlKnowStoreCourseContentModel::where('product_id', $v['p_product_id'])->count();
                    } else {
                        $v['catalog_number'] = ZxlKnowStoreCourseContentModel::where('product_id', $v['product_id'])->count();
                    }

                    $v['content_id'] = ZxlKnowStoreCourseContentModel::where(['product_id' => $v['product_id']])->order(['id' => 'asc'])->value('id');
                }
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
            return json(['code' => 0,'msg' => 'SUCCESS','count' => $list['total'],'data' => $list['data']]);
        }
        return $this->fetch();
    }

    /**
     * 我的考试
     * 
     * @return mixed
     */
    public function exam()
    {
        if ($this->request->isPost()) {
            $limit = $this->request->param('limit');
            $page = $this->request->param('page',1);
            $keyword = $this->request->param('keyword');
            
            $m_id = $this->request->m_id;
            try {
                //查询条件
                $where = function($q)use($m_id, $keyword){
                    $q->where('up.m_id', $m_id);
                    $q->where('up.user_id', $this->user_id);
                    $q->where('up.power_type', 10);
                    if ($keyword != '') {
                        $q->where('p.name|p.sub_title', 'like','%'.trim($keyword).'%');
                    }
                };
                $query = ZxlKnowStorePowerModel::alias('up')->where($where)->leftJoin('zxl_know_store_product p','up.product_id = p.id');
                $list = $query->field('up.*,p.name,p.sub_title,p.p_product_id,p.head_imgs,p.background_color,p.virtual_sales,p.real_sales')->order('create_time', 'desc')->paginate($limit,false,['page'=>$page])->toArray();
                foreach ($list['data'] as &$v) {
                    $v['head_imgs'] = '/static/images/exam.png';
                    $v['product_type_text'] = ZxlKnowStoreProductModel::getPcProductType($v['power_type']);

                    if($v['end_time'] == 0) {
                        $v['end_time'] = "永久有效";
                    } else {
                        $v['end_time'] = date("Y-m-d H:i:s", $v['end_time']);
                    }
                    $v['question_num'] = ZxlKnowStoreExamContentModel::get_question_num($v['product_id']);
                }
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
            return json(['code' => 0,'msg' => 'SUCCESS','count' => $list['total'],'data' => $list['data']]);
        }
        return $this->fetch();
    }

    /**
     * 我的考试记录
     * 
     * @return mixed
     */
    public function exam_log()
    {
        $product_id = $this->request->param('product_id');

        $this->assign('product_id', $product_id);
        return $this->fetch();
    }

    /**
     * 我的直播课
     * 
     * @return mixed
     */
    public function live()
    {
        if ($this->request->isPost()) {
            $limit = $this->request->param('limit');
            $page = $this->request->param('page',1);
            $keyword = $this->request->param('keyword');
            
            $m_id = $this->request->m_id;
            try {
                //查询条件
                $where = function($q)use($m_id, $keyword){
                    $q->where('c.m_id', $m_id);
                    $q->where('c.student_ids', 'REGEXP', $this->user_id);
                    if ($keyword != '') {
                        $q->where('p.name|p.sub_title', 'like','%'.trim($keyword).'%');
                    }
                };
                $query = ZxlKnowStoreLiveClassModel::alias('c')->where($where)->leftJoin('zxl_know_store_product p','c.product_id = p.id');
                $list = $query->field('c.*,p.name as product_name,p.product_type,p.head_imgs')->order('create_time', 'desc')->paginate($limit,false,['page'=>$page])->toArray();
                foreach ($list['data'] as &$v) {
                    $v['head_imgs'] = $v['head_imgs'] ? explode(',',$v['head_imgs'])[0] : '/static/images/no_pic_1.png';
                    $v['attr'] = ZxlKnowStoreProductAttrModel::find($v['attr_id']);
                    $v['product_type_text'] = ZxlKnowStoreProductModel::getPcProductType($v['product_type']);
                    $v['status_text'] = ZxlKnowStoreLiveClassModel::getStatus($v['status']);
                    $v['max_users'] = ZxlKnowStoreProductModel::get_max_users($v['max_users']);
                    
                    $v['hour'] = ZxlKnowStoreLiveClassHourModel::get_hour($v['id']);
                }
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
            return json(['code' => 0,'msg' => 'SUCCESS','count' => $list['total'],'data' => $list['data']]);
        }
        return $this->fetch();
    }

    /**
     * 我的题库
     * 
     * @return mixed
     */
    public function question_bank()
    {
        if ($this->request->isPost()) {
            $limit = $this->request->param('limit');
            $page = $this->request->param('page',1);
            $keyword = $this->request->param('keyword');
            
            $m_id = $this->request->m_id;
            try {
                //查询条件
                $where = function($q)use($m_id, $keyword){
                    $q->where('up.m_id', $m_id);
                    $q->where('up.user_id', $this->user_id);
                    $q->where('up.power_type', 5);
                    if ($keyword != '') {
                        $q->where('p.name|p.sub_title', 'like','%'.trim($keyword).'%');
                    }
                };
                $query = ZxlKnowStorePowerModel::alias('up')->where($where)->leftJoin('zxl_know_store_product p','up.product_id = p.id');
                $list = $query->field('up.*,p.name,p.p_product_id,p.head_imgs,p.virtual_sales,p.real_sales')->order('create_time', 'desc')->paginate($limit,false,['page'=>$page])->toArray();
                foreach ($list['data'] as &$v) {
                    $v['head_imgs'] = $v['head_imgs'] ? explode(',',$v['head_imgs'])[0] : '/static/images/no_pic_1.png';
                    $v['product_type_text'] = ZxlKnowStoreProductModel::getPcProductType($v['power_type']);

                    if($v['end_time'] == 0) {
                        $v['end_time'] = "永久有效";
                    } else {
                        $v['end_time'] = date("Y-m-d H:i:s", $v['end_time']);
                    }

                    // 题目数
                    if ($v['p_product_id']) {
                        $v['question_number'] = ZxlKnowStoreQuestionModel::where('lib_id', $v['p_product_id'])->count();
                    } else {
                        $v['question_number'] = ZxlKnowStoreQuestionModel::where('lib_id', $v['product_id'])->count();
                    }
                    
                }
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
            return json(['code' => 0,'msg' => 'SUCCESS','count' => $list['total'],'data' => $list['data']]);
        }
        return $this->fetch();
    }

    /**
     * 我的兑换
     * 
     * @return mixed
     */
    public function exchange()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $m_id = $this->request->m_id;

            Db::startTrans(); // 开启事务回滚
            try {
                $knowStoreApiService = new KnowStoreApiService($m_id, $this->user_token);
                $result = $knowStoreApiService->markingCode($post['code']);
                if ($result) {
                    Db::commit();
                    return json(['code' => 0, 'msg' => '兑换成功']);
                }
            } catch (\Exception $e){
                Db::rollback();
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
        }
        return $this->fetch();
    }

    /**
     * 兑换码-兑换商品记录
     * 
     * @return json
     */
    public function exchange_log()
    {
        if ($this->request->isPost()) {
            $limit = $this->request->param('limit');
            $page = $this->request->param('page',1);
            $type = $this->request->param('type',1);
            $m_id = $this->request->m_id;
            try {
                if ($type == 1) {
                    //查询条件
                    $where = function($q)use($m_id){
                        $q->where('cl.m_id', $m_id);
                        $q->where('cl.user_id', $this->user_id);
                    };
                    $query = ZxlApplyRedeemCodeLogModel::alias('cl')->where($where)->leftJoin('zxl_apply_redeem_code c','cl.code_id = c.id');
                    $list = $query->field('cl.*,c.course_id')->order('create_time', 'desc')->paginate($limit,false,['page'=>$page])->toArray();
                    foreach ($list['data'] as &$v) {
                        $attr_list = ZxlKnowStoreProductAttrModel::whereIn('id', $v['course_id'])->field('id,product_id,name')->select()->toArray();
                        foreach ($attr_list as &$attr) {
                            $product = ZxlKnowStoreProductModel::find($attr['product_id']);
                            $attr['product_name'] = $product['name'];
                            $attr['head_imgs'] = $product['head_imgs'];
                            $attr['product_type'] = $product['product_type'];

                            $attr['head_imgs'] = $attr['head_imgs'] ? explode(',',$attr['head_imgs'])[0] : '/static/images/no_pic_1.png';
                            $attr['product_type_text'] = ZxlKnowStoreProductModel::getPcProductType($attr['product_type']);
                        }
                        $v['course_list'] = $attr_list;
                        // 兑换时间
                        $v['use_time'] = date("Y-m-d H:i:s", $v['use_time']);
                    }
                } else if ($type == 2) {
                    $list = $this->get_savings_card_log($m_id, $limit, $page);
                } else if ($type == 3) {
                    $list = $this->get_member_level_log($m_id, $limit, $page);
                }
                
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
            return json(['code' => 0,'msg' => 'SUCCESS','count' => $list['total'],'data' => $list['data']]);
        }
    }

    /**
     * 获取兑换省钱卡记录
     * 
     * @return array
     */
    private function get_savings_card_log($m_id, $limit, $page)
    {
        $where = function($q)use($m_id){
            $q->where('m_id', $m_id);
            $q->where('user_id', $this->user_id);
        };
        $list = ZxlKnowStoreSavingsCardNumberModel::with(["card"])->where($where)->field("id, card_id, number, use_time, password")->order("create_time", "desc")->paginate($limit,false,['page'=>$page])->toArray();
        foreach ($list['data'] as &$v) {
            $v['img'] = 'https://api.zixunli.cn/uploads/images/save_card.jpg';
            $v['use_time'] = date("Y-m-d H:i:s", $v['use_time']);
        }
        return $list;
    }

    /**
     * 获取兑换会员卡记录
     * 
     * @return array
     */
    private function get_member_level_log($m_id, $limit, $page)
    {
        $where = function($q)use($m_id){
            $q->where('m_id', $m_id);
            $q->where('user_id', $this->user_id);
        };
        $list = ZxlKnowStoreMemberLevelCardModel::with(["level"])->where($where)->field("id, level_id, number, use_time, password, valid_date")->order("create_time", "desc")->paginate($limit,false,['page'=>$page])->toArray();
        foreach ($list['data'] as &$v) {
            $v["img"] = "https://api.zixunli.cn/uploads/images/vip_card.jpg";
            $v["valid_date"] = ZxlKnowStoreMemberLevelModel::RULESTR[$v['valid_date']];
            $v['use_time'] = date("Y-m-d H:i:s", $v['use_time']);
        }
        return $list;
    }

    /**
     * 记录点赞
     * 
     * @return json
     */
    public function like()
    {
        if ($this->request->isPost()) {

            $id = $this->request->param('id');
            $like_type = $this->request->param('like_type'); // 1 文章 2 文章评论 3考试记录

            Db::startTrans(); // 开启事务回滚
            try {
                $model = ZxlKnowStoreLikeLogModel::where(['user_id' => $this->user_id, 'target_id' => $id])->find();
                if (!$model) {
                    $model = new ZxlKnowStoreLikeLogModel();
                    $model->user_id = $this->user_id;
                    $model->like_type = $like_type;
                    $model->target_id = $id;
                    $model->create_time = time();
                    $model->update_time = time();
                    if ($model->save()) {
                        if ($like_type == 3) {
                            $practice = ZxlKnowStoreQuestionPracticeModel::find($id);
                            $practice->like += 1;
                            $practice->save();
                        }
                    }
                }
                Db::commit();
                return json(['code' => 0,'msg' => '点赞成功']);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
        }
    }

    /**
     * 取消点赞
     * 
     * @return json
     */
    public function unlike()
    {
        if ($this->request->isPost()) {

            $id = $this->request->param('id');
            $like_type = $this->request->param('like_type'); // 1 文章 2 文章评论 3考试记录

            Db::startTrans(); // 开启事务回滚
            try {
                $result = ZxlKnowStoreLikeLogModel::where(['user_id' => $this->user_id, 'target_id' => $id, 'like_type' => $like_type])->delete();
                if ($result) {
                    if ($like_type == 3) {
                        $practice = ZxlKnowStoreQuestionPracticeModel::find($id);
                        $practice->like -= 1;
                        $practice->save();
                    }
                    Db::commit();
                    return json(['code' => 0,'msg' => '取消成功']);
                } else {
                    Db::rollback();
                    return json(['code' => 1,'msg' => '取消失败']);
                }
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
            
        }
    }
}